package ru.belokuriha_online.resort_hotels_belokuriha;


import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;

import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;

import android.widget.ImageButton;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import android.view.*;
import android.content.*;
import android.content.DialogInterface.OnClickListener;
import android.widget.ListView;
import android.database.sqlite.*;
import android.database.*;
import android.os.*;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.widget.*;
import android.graphics.drawable.*;
import android.net.*;


public class Favorits extends Activity {


	String filepricesPath1;	
	String fileaboutPath;
	String namesan;
	String id_namesan;
	String namesanp;
	String id_namesanp;
	String spprisepath;
	String spprisepathfull;

	ArrayList<HashMap<String, String>> Datams;

	HashMap<String, String> msan;

	SimpleAdapter favorAdapter;

	CharSequence[] spisokcontmenuf;
	AlertDialog.Builder dialogcontmenu;
	AlertDialog.Builder delbuilder;
	AlertDialog.Builder builderdellfavorit, builderdellfavorit1;
	TextView noseach;
	int FlagOnlain;

	//beg_var
	Favorsql sqldbc;
	SQLiteDatabase sqldb;
	ListView listsan_favorits;
	ImageButton favoritsClear;
	ImageButton exithome;
	ImageButton ntel;
	ImageButton ButtonShare;
	SwipeForElList swipeEl;

	ArrayList<HashMap<String, String>> dataf;
	HashMap<String, String> dataf_i;
	//end_var

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.favoritlist);
		//beg

		spisokcontmenuf = getResources().getTextArray(R.array.contmenufavor);
		spprisepath = getIntent().getExtras().getString("spprisepath");
		spprisepathfull = getIntent().getExtras().getString("spprisepathfull");
		FlagOnlain = getIntent().getExtras().getInt("FlagOnlain");
		listsan_favorits = (ListView) findViewById(R.id.listfavorits);
		favoritsClear = (ImageButton) findViewById(R.id.favoritsClear);
		exithome =(ImageButton) findViewById(R.id.imageButtonHome);
		ntel =(ImageButton) findViewById(R.id.favoritTel);
		ButtonShare =(ImageButton) findViewById(R.id.imageButtonShare);
		delbuilder = new AlertDialog.Builder(this);
		builderdellfavorit = new AlertDialog.Builder(this);
		builderdellfavorit1 = new AlertDialog.Builder(this);
		favoritHandler();
		//end

		// Обнаружение свайпа
		swipeEl = new SwipeForElList();
		listsan_favorits.setOnTouchListener(swipeEl);
		listsan_favorits.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, final int position,long id) {	
				// Если был обнаружен свайп, то удаляем элемент
				if (swipeEl.swipeDetected()){
					if (swipeEl.getAction() == SwipeForElList.Action.LR || 
							swipeEl.getAction() == SwipeForElList.Action.RL)
					{
						//удаляем элемент

						try {
							favoritdel(position);

						} catch (Exception e) {

						}


					}
				} else {
					// TODO Auto-generated method stub
					final String description_calendar1 = dataf.get(position).get("f_0").toString()+" / " + dataf.get(position).get("f_1").toString()+ " / " +
					dataf.get(position).get("f_2").toString()+" / " + dataf.get(position).get("f_3").toString()+" / " + dataf.get(position).get("f_4").toString()+" / " +
					dataf.get(position).get("f_5").toString()+" (" +dataf.get(position).get("f_7").toString() + ") "+
					" ....... " + dataf.get(position).get("f_6").toString() +" "+getString(R.string.hotel_prise);
					builderdellfavorit1.setTitle("");		
					builderdellfavorit1.setItems(spisokcontmenuf, 
							new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int item) {
							switch (item) {
								case 0:
									try { 
										favoritdel(position);				
									} catch (Exception e) {
			
									}
								break;
								case 1:
									try { 
										Intent calendarIntent1 = new Intent(Intent.ACTION_INSERT);
										calendarIntent1.setType("vnd.android.cursor.item/event"); 
										calendarIntent1.putExtra(Events.TITLE, getString(R.string.calend_title));
										calendarIntent1.putExtra(Events.EVENT_LOCATION, dataf.get(position).get("f_0").toString() + " "+ getString(R.string.location));
										calendarIntent1.putExtra(Events.DESCRIPTION, description_calendar1);					                 
						                calendarIntent1.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true); 
						                calendarIntent1.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,System.currentTimeMillis()); 
						                calendarIntent1.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,System.currentTimeMillis()); 
						                startActivity(calendarIntent1);				
									} catch (Exception e) {
			
									}
								break;
								case 2:
									try {			
										//
										Intent sendIntent = new Intent();
										sendIntent.setAction(Intent.ACTION_SEND);
										sendIntent.putExtra(Intent.EXTRA_TEXT, description_calendar1);
										sendIntent.setType("text/plain");
										startActivity(sendIntent);
										//
									} catch (Exception e) {

									}
								break;
							}

						}
					}).create().show();

					return;
					
				}

				//else
				//	return;			
			}
		});

		listsan_favorits.setOnItemLongClickListener(new OnItemLongClickListener() { 
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					final int position, long id) {

				// TODO Auto-generated method stub
				final String description_calendar = dataf.get(position).get("f_0").toString()+" / " + dataf.get(position).get("f_1").toString()+ " / " +
				dataf.get(position).get("f_2").toString()+" / " + dataf.get(position).get("f_3").toString()+" / " + dataf.get(position).get("f_4").toString()+" / " +
				dataf.get(position).get("f_5").toString()+" (" +dataf.get(position).get("f_7").toString() + ") "+
				" ....... " + dataf.get(position).get("f_6").toString() +" "+getString(R.string.hotel_prise);
				builderdellfavorit.setTitle("");		
				builderdellfavorit.setItems(spisokcontmenuf, 
						new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int item) {
						switch (item) {
							case 0:
								try { 
									favoritdel(position);				
								} catch (Exception e) {
		
								}
							break;
							case 1:
								try { 
									Intent calendarIntent = new Intent(Intent.ACTION_INSERT);
									calendarIntent.setType("vnd.android.cursor.item/event"); 
									calendarIntent.putExtra(Events.TITLE, getString(R.string.calend_title));
									calendarIntent.putExtra(Events.EVENT_LOCATION, dataf.get(position).get("f_0").toString() + " "+ getString(R.string.location));
									calendarIntent.putExtra(Events.DESCRIPTION, description_calendar);					                 
					                calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true); 
					                calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,System.currentTimeMillis()); 
					                calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,System.currentTimeMillis()); 
					                startActivity(calendarIntent);				
								} catch (Exception e) {
		
								}
							break;
							case 2:
								try {			
									//
									Intent sendIntent = new Intent();
									sendIntent.setAction(Intent.ACTION_SEND);
									sendIntent.putExtra(Intent.EXTRA_TEXT, description_calendar);
									sendIntent.setType("text/plain");
									startActivity(sendIntent);
									//
								} catch (Exception e) {

								}
							break;
						}

					}
				}).create().show();

				return false;
			} 
		});
		listsan_favorits.setOnScrollListener(new OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == 0) {
					//ButtonShare.setVisibility(view.VISIBLE);
				} else {
					//ButtonShare.setVisibility(view.GONE);
				}
			}
			public void onScroll(AbsListView view, int firstVisibleItem, 
					int visibleItemCount, int totalItemCount) {

			} 	
		});
		
		ButtonShare.setOnClickListener(new View.OnClickListener() {
			TransitionDrawable ShareTransition = (TransitionDrawable)getApplicationContext().getResources().getDrawable(R.drawable.transition_share);	
			public void onClick(View v) {

				try {			
					ButtonShare.setImageDrawable(ShareTransition);
					ShareTransition.startTransition(1000);
					//
					Intent sendIntent = new Intent();
					sendIntent.setAction(Intent.ACTION_SEND);
					sendIntent.putExtra(Intent.EXTRA_TEXT, Sharefavor());
					sendIntent.setType("text/plain");
					startActivity(sendIntent);
					//
				} catch (Exception e) {

				}
			}	
		});
		favoritsClear.setOnClickListener(new View.OnClickListener() {
			TransitionDrawable clearTransition = (TransitionDrawable)getApplicationContext().getResources().getDrawable(R.drawable.transition_delete);
			public void onClick(View v) {
				try {
					favoritsClear.setImageDrawable(clearTransition);
					clearTransition.startTransition(1000);
					if (dataf.size() > 0) {
						delbuilder.setTitle(R.string.delt_itpr);
						delbuilder.setMessage(R.string.delm_itpr);
						delbuilder.setNegativeButton(R.string.deln_itpr, null);
						delbuilder.setPositiveButton(R.string.dely_itpr, new OnClickListener() {
							public void onClick(DialogInterface arg0, int arg1) {
								String delall = "DELETE FROM " + Favorsql.dtable + " ";
								Favorsql sqldbcdel_all = new Favorsql(getApplicationContext());
								SQLiteDatabase sqldbdel_all = sqldbcdel_all.getWritableDatabase();
								sqldbdel_all.execSQL(delall);
								sqldbdel_all.close();
								sqldbcdel_all.close();
								favoritHandler();
								favorAdapter.notifyDataSetChanged();
							}
						}).create().show();
					}
				} catch (Exception e) {

				}

			}	
		});
		exithome.setOnClickListener(new View.OnClickListener() {
			TransitionDrawable HomTransition = (TransitionDrawable)getApplicationContext().getResources().getDrawable(R.drawable.transition_hom);
			public void onClick(View v) {
				exithome.setImageDrawable(HomTransition);
				HomTransition.startTransition(1000);
				setResult(3);
				finish();	
			}	
		});
		ntel.setOnClickListener(new View.OnClickListener() {
			TransitionDrawable TelfTransition = (TransitionDrawable)getApplicationContext().getResources().getDrawable(R.drawable.transition_telef);	
			public void onClick(View v) {

				try {			
					ntel.setImageDrawable(TelfTransition);
					TelfTransition.startTransition(1000);
					String stel = getString(R.string.telefonmob);
					Intent diallintent = new Intent(Intent.ACTION_DIAL,Uri.parse(stel));
					startActivity(diallintent);
				} catch (Exception e) {

				}
			}	
		});


	}
	public String Sharefavor() {
		int i;
		String share_san = "";
		try {
			if (dataf != null) {
				if (dataf.size() > 0) {
					for (i = 0; i < dataf.size(); i++) {					
						share_san = share_san + (i+1) + ") " +
								dataf.get(i).get("f_0").toString()+" / " + dataf.get(i).get("f_1").toString()+ " / " +
								dataf.get(i).get("f_2").toString()+" / " + dataf.get(i).get("f_3").toString()+" / " + dataf.get(i).get("f_4").toString()+" / " +
								dataf.get(i).get("f_5").toString()+" (" +dataf.get(i).get("f_7").toString() + ") "+
								" ....... " + dataf.get(i).get("f_6").toString() +" "+getString(R.string.hotel_prise)+"\n";
						
					}
					
				}			
			}			
		} catch (Exception e) {
			
		}
		
		return share_san;
	}
	public void favoritdel(final int position) {
		delbuilder.setTitle(R.string.delt_itpr);
		delbuilder.setMessage(R.string.delm_itpr);
		delbuilder.setNegativeButton(R.string.deln_itpr, null);
		delbuilder.setPositiveButton(R.string.dely_itpr, new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				String delEl = "DELETE FROM " + Favorsql.dtable + 
						" 	WHERE ("+ Favorsql.DFAVORSAN + " = '" + dataf.get(position).get("f_0").toString() + "') AND (" 
						+ Favorsql.DFAVORCATEGORY + " = '" + dataf.get(position).get("f_1").toString() + "') AND ("
						+ Favorsql.DFAVORAREAN + " = '" + dataf.get(position).get("f_2").toString() + "') AND ("
						+ Favorsql.DFAVORRAZM + " = '" + dataf.get(position).get("f_3").toString() + "') AND ("
						+ Favorsql.DFAVORTIME + " = '" + dataf.get(position).get("f_4").toString() + "') AND ("
						+ Favorsql.DFAVORFOOD + " = '" + dataf.get(position).get("f_5").toString() + "') AND ("
						+ Favorsql.DFAVORPRICE +  " = '" + dataf.get(position).get("f_6").toString() + "')" +
						" ";
				Favorsql sqldbcdel_el  = new Favorsql(getApplicationContext());
				SQLiteDatabase sqldbdel_el = sqldbcdel_el.getWritableDatabase();
				sqldbdel_el.execSQL(delEl);
				sqldbdel_el.close();
				sqldbcdel_el.close();
				favoritHandler();
				favorAdapter.notifyDataSetChanged();
			}
		}).create().show();
	}	
	public void favoritHandler() {
		Handler handlerListFavorits = new Handler();
		handlerListFavorits.post(new Runnable() {
			@Override
			public void run() {				
				listFavoritsHotel();
			}
		});
	}

	private void listFavoritsHotel() {

		try {
			String selblt = "SELECT " + Favorsql.DFAVORSAN + ", "	+ Favorsql.DFAVORCATEGORY + ", " + Favorsql.DFAVORAREAN + ", " + Favorsql.DFAVORRAZM + ", " + Favorsql.DFAVORTIME + ", " + Favorsql.DFAVORFOOD + ", " + 
					Favorsql.DFAVORPRICE + ", " + Favorsql.DFAVORPRIM +
					" FROM " + Favorsql.dtable+
					" ORDER BY "+ Favorsql.DFAVORSAN + " ";


			// �������������� ��� �����
			Favorsql sqldbchotel = new Favorsql(getApplicationContext());
			// ���� ������ � ������
			SQLiteDatabase sqldbhotel = sqldbchotel.getWritableDatabase();

			Cursor  cursorbl0 = sqldbhotel.rawQuery(selblt, null);


			int ctbl1 =  cursorbl0.getCount();
			dataf =  new ArrayList<HashMap<String, String>>();

			int contpoz = 0;
			double sumpoz = (double) 0;
			if (ctbl1 > 0)
			{

				while (cursorbl0.moveToNext()) {

					dataf_i = new HashMap<String, String>();
					dataf_i.put("f_0", cursorbl0.getString(0));
					dataf_i.put("f_1", cursorbl0.getString(1));
					dataf_i.put("f_2", cursorbl0.getString(2));
					dataf_i.put("f_3", cursorbl0.getString(3));
					dataf_i.put("f_4", cursorbl0.getString(4));
					dataf_i.put("f_5", cursorbl0.getString(5));
					dataf_i.put("f_6", Double.valueOf(cursorbl0.getDouble(6)).toString());
					dataf_i.put("f_7", cursorbl0.getString(7));
					dataf.add(dataf_i);

				}

			} 
			cursorbl0.close();
			sqldbhotel.close();
			sqldbchotel.close(); 

			String[] from = {"f_0","f_1","f_2","f_3","f_4","f_5","f_6","f_7"};
			int[] to = {R.id.favor_san,R.id.favor_category,R.id.favor_area_n,R.id.favor_razm,R.id.favor_time,R.id.favor_food,R.id.favor_price,R.id.favor_prim}; 

			//  
			favorAdapter = new SimpleAdapter(this, dataf, R.layout.favorit_item, from, to);

			favorAdapter.notifyDataSetChanged();
			listsan_favorits.setAdapter(favorAdapter);
		}
		catch (Exception e)
		{}
	}






	public boolean onCreateOptionsMenu(Menu menu) { 

		getMenuInflater().inflate(R.menu.pmenu, menu);

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) { 

		if (FlagOnlain == 0) {
			menu.findItem(R.id.loaditem1).setVisible(true);
			menu.findItem(R.id.loaditem1).setEnabled(true);
		} else
		{			
			menu.findItem(R.id.loaditem1).setEnabled(false);
			menu.findItem(R.id.loaditem1).setVisible(false);
		}
		menu.findItem(R.id.pitem2).setEnabled(true);
		menu.findItem(R.id.abitem3).setEnabled(true);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) { 

		case R.id.loaditem1: 
			GoMain();
			break; 


		case R.id.pitem2:

			try {
				Intent Preferintent = new Intent(getApplicationContext(),PreferActivity.class);
				Preferintent.putExtra("FlagOnlain", FlagOnlain);
				startActivityForResult(Preferintent, 0);
			} catch (Exception e) {

			}
			break; 
		case R.id.abitem3: 

			try {
				Intent intentapp = new Intent(getApplicationContext(), Aboutapp.class);
				intentapp.putExtra("FlagOnlain", FlagOnlain);
				startActivityForResult(intentapp, 0);
			} catch (Exception e) {

			}
			break;
		}   

		return super.onOptionsItemSelected(item); 

	}
	private void GoMain() {
		AlertDialog.Builder buildergomain = new AlertDialog.Builder(this);
		buildergomain.setTitle(R.string.lt_app);		
		buildergomain.setMessage(R.string.lmmm_app);		
		buildergomain.setNegativeButton(R.string.qn_app, null);
		buildergomain.setPositiveButton(R.string.qy_app, new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				setResult(7);
				finish(); 	            	

			}
		}).create().show();	
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == 7) {
			setResult(7);
			finish();
		}
		//
		if (resultCode ==  5) {
			try {
				openOptionsMenu();
			} catch (Exception e) {

			}
		}
		if (resultCode ==  9) {
			try {
				Intent Preferintent = new Intent(getApplicationContext(),PreferActivity.class);
				Preferintent.putExtra("FlagOnlain", FlagOnlain);
				startActivityForResult(Preferintent,0);
			} catch (Exception e) {

			}
		}
		if (resultCode ==  10) {
			try{
				Intent intentapp = new Intent(getApplicationContext(), Aboutapp.class);
				intentapp.putExtra("FlagOnlain", FlagOnlain);
				startActivityForResult(intentapp,0);	
			} catch (Exception e) {

			}
		}

	}

	@Override
	public void onBackPressed() {
		setResult(2);
		finish();
	}	

}
